<template>
  <div class="order-detail">
    <div class="container">
      <el-card class="order-card">
        <!-- 订单基本信息 -->
        <div class="order-header">
          <div class="order-info">
            <h2>订单详情</h2>
            <div class="order-meta">
              <span>订单号：{{ orderInfo.order?.orderNo }}</span>
              <span>下单时间：{{ formatDate(orderInfo.order?.createTime) }}</span>
              <span class="order-status">{{ getStatusText(orderInfo.order?.status) }}</span>
              <el-button v-if="orderInfo.order?.status === 1" type="primary" @click="handleShipOrder">模拟商家发货</el-button>
              <el-button v-if="orderInfo.order?.status === 2" type="primary" @click="handleFinishOrder">模拟已收货</el-button>
            </div>
          </div>
        </div>

        <!-- 物流追踪信息 - 仅在已发货状态显示 -->
        <div v-if="orderInfo.order?.status === 2" class="logistics-simple">
          <h3>物流状态</h3>
          <div class="logistics-container">
            <div class="delivery-info">
              <div class="logistics-header">
                <div class="logistics-status">
                  <i class="el-icon-truck"></i>
                  <span>运输中</span>
                </div>
                <el-button 
                  type="primary" 
                  @click="viewLogisticsDetails" 
                  class="view-logistics-btn"
                >
                  查看完整物流详情
                </el-button>
              </div>
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in logisticsInfo.slice(0, 3)"
                  :key="index"
                  :timestamp="activity.timestamp"
                  :type="activity.type"
                >
                  {{ activity.content }}
                </el-timeline-item>
              </el-timeline>
              <p>预计送达时间：3-5天内</p>
              <p>配送方式：快递配送</p>
            </div>
          </div>
        </div>

        <!-- 商品列表 -->
        <div class="product-list">
          <el-empty v-if="!orderInfo.orderItems?.length" description="暂无商品信息" />
          <div v-else v-for="item in orderInfo.orderItems" :key="item.id" class="product-item">
            <el-image :src="item.itemImage" :alt="item.itemName" class="product-image" />
            <div class="product-info">
              <h4>{{ item.itemName }}</h4>
              <div class="product-price">
                <span class="price">¥{{ item.price?.toFixed(2) }}</span>
                <span class="count">x{{ item.quantity }}</span>
                <span class="total-price">小计：¥{{ item.totalPrice?.toFixed(2) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单金额信息 -->
        <div class="order-amount">
          <div class="amount-item">
            <span>商品总额：</span>
            <span>¥{{ orderInfo.order?.itemAmount?.toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span>运费：</span>
            <span>¥{{ orderInfo.order?.freightAmount?.toFixed(2) }}</span>
          </div>
          <div class="amount-item">
            <span>优惠金额：</span>
            <span>¥{{ orderInfo.order?.discountAmount?.toFixed(2) }}</span>
          </div>
          <div class="amount-item total">
            <span>实付金额：</span>
            <span class="total">¥{{ orderInfo.order?.payAmount?.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 收货信息 -->
        <div class="delivery-info">
          <h3>收货信息</h3>
          <div class="info-content">
            <p>收货人：{{ orderInfo.order?.recipientName }}</p>
            <p>联系电话：{{ orderInfo.order?.recipientPhone }}</p>
            <p>收货地址：{{ formatAddress(orderInfo.order) }}</p>
            <p>邮政编码：{{ orderInfo.order?.postalCode }}</p>
          </div>
        </div>

        <!-- 订单操作按钮 -->
        <div class="order-actions">
          <el-button 
            v-if="orderInfo.order?.status === 0" 
            type="primary"
            @click="handlePay"
          >
            立即付款
          </el-button>
          <el-button 
            v-if="orderInfo.order?.status === 3" 
            type="danger"
            size="large"
            icon="Star"
            @click="handleReview"
          >
            立即评价
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getOrderById, shipOrder, finishOrder } from '@/api/order'

const route = useRoute()
const router = useRouter()

// 物流信息数据
const logisticsInfo = ref([
  {
    timestamp: '2024-01-20 18:30',
    content: '快件已签收，签收人：张三',
    type: 'success'
  },
  {
    timestamp: '2024-01-20 14:20',
    content: '快件已到达【北京市朝阳区某某站点】',
    type: 'primary'
  },
  {
    timestamp: '2024-01-19 08:15',
    content: '快件已从【上海市某某集散中心】发出',
    type: 'primary'
  },
  {
    timestamp: '2024-01-18 20:45',
    content: '商家已发货',
    type: 'primary'
  }
])

// 订单数据
const orderInfo = ref({
  order: null,
  orderItems: []
})

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '已支付',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 格式化地址
const formatAddress = (order) => {
  if (!order) return ''
  return `${order.province}${order.city}${order.district}${order.addressDetail}`
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  try {
    const localDate = new Date(date)
    return localDate.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
  } catch (error) {
    console.error('日期格式化失败：', error)
    return '日期格式错误'
  }
}

// 处理支付
const handlePay = () => {
  router.push({
    path: '/payment',
    query: {
      id: orderInfo.value.order.id,
      method: 'alipay'
    }
  })
}

// 模拟已收货
const handleFinishOrder = async () => {
  try {
    await finishOrder(orderInfo.value.order.id)
    ElMessage.success('已收货成功')
    fetchOrderDetail()
  } catch (error) {
    console.error('已收货失败：', error)
    ElMessage.error('已收货失败，请重试')
  }
}

// 模拟商家发货
const handleShipOrder = async () => {
  try {
    await shipOrder(orderInfo.value.order.id)
    ElMessage.success('发货成功')
    fetchOrderDetail()
  } catch (error) {
    console.error('发货失败：', error)
    ElMessage.error('发货失败，请重试')
  }
}

// 处理评价
const handleReview = () => {
  // 跳转到商品详情页的评论区
  if (orderInfo.value.orderItems && orderInfo.value.orderItems.length > 0) {
    // 获取第一个商品的ID作为跳转目标
    const firstItem = orderInfo.value.orderItems[0]
    const productId = firstItem.productId || firstItem.itemId || firstItem.spuId // 根据实际字段名调整
    
    if (!productId) {
      ElMessage.warning('无法获取商品ID')
      return
    }
    
    router.push({
      path: '/goods/detail',
      query: {
        id: productId,
        orderId: orderInfo.value.order.id,
        scrollToComment: 'true'
      }
    })
  } else {
    ElMessage.warning('没有找到可评价的商品')
  }
}

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const orderId = route.params.id
    const res = await getOrderById(orderId)
    if (res) {
      orderInfo.value = res
    }
  } catch (error) {
    console.error('获取订单详情失败：', error)
    ElMessage.error('获取订单详情失败')
  }
}

// 查看完整物流详情
const viewLogisticsDetails = () => {
  // 获取收件地址信息
  const address = formatAddress(orderInfo.value.order)
  const recipientInfo = {
    name: orderInfo.value.order?.recipientName,
    phone: orderInfo.value.order?.recipientPhone,
    address: address,
    postalCode: orderInfo.value.order?.postalCode
  }
  
  // 获取订单项列表，简化后传递给物流页面
  const orderItems = orderInfo.value.orderItems ? orderInfo.value.orderItems.map(item => ({
    id: item.id,
    itemId: item.itemId || item.productId || item.spuId, // 根据实际字段名调整
    name: item.itemName,
    image: item.itemImage,
    quantity: item.quantity,
    price: item.price || 0
  })) : []
  
  // 获取第一个订单项的ID作为默认选中项
  const defaultItemId = orderItems.length > 0 ? orderItems[0].id : null
  
  // 跳转到物流追踪页面，传递订单ID、收件人信息和订单项列表
  router.push({
    name: 'LogisticsTracking',
    params: {
      orderId: orderInfo.value.order.id
    },
    query: {
      recipientInfo: JSON.stringify(recipientInfo),
      orderItems: JSON.stringify(orderItems),
      defaultItemId: defaultItemId
    }
  })
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style lang="scss" scoped>
.order-detail {
  padding: 20px 0;
  background-color: #f5f5f5;
  min-height: calc(100vh - 200px);
}

.container {
  width: 1200px;
  margin: 0 auto;
}

.order-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.order-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.order-header h2 {
  color: #ff4d4f;
  margin-bottom: 15px;
}

.order-meta {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #666;
}

.order-status {
  color: #ff4d4f;
  font-weight: bold;
}

.payment-status {
  color: #67c23a;
  font-weight: bold;
}

.product-list {
  padding: 20px;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 15px;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-color: #ff4d4f;
  }

  &:last-child {
    margin-bottom: 0;
  }
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  margin-right: 20px;
  border-radius: 4px;
}

.product-info {
  flex: 1;
}

.product-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 15px;
}

.price {
  color: #ff4d4f;
  font-weight: bold;
}

.count {
  color: #666;
}

.total-price {
  color: #666;
  font-size: 14px;
}

.order-amount {
  padding: 20px;
  border-top: 1px solid #e8e8e8;
  text-align: right;
}

.amount-item {
  margin: 10px 0;
  color: #666;

  &.total {
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #e8e8e8;
    color: #333;
    font-weight: bold;
  }
}

.total {
  color: #ff4d4f;
  font-size: 20px;
  margin-left: 10px;
}

.delivery-info {
  padding: 20px;
  border-top: 1px solid #e8e8e8;
}

.delivery-info h3 {
  color: #333;
  margin-bottom: 15px;
}

.info-content {
  color: #666;
}

.info-content p {
  margin: 8px 0;
}

.order-actions {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #e8e8e8;

  .el-button {
    margin-left: 10px;

    &--primary {
      background-color: #ff4d4f;
      border-color: #ff4d4f;

      &:hover {
        background-color: #ff7875;
        border-color: #ff7875;
      }
    }
  }
}

.logistics-map {
  margin: 20px 0;
}

.delivery-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.el-timeline {
  margin: 20px 0;
}

.map-container {
  margin-top: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.map-wrapper {
  position: relative;
  min-height: 150px;
}

.delivery-route {
  position: relative;
  padding: 20px 0;
}

.location {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.location i {
  color: var(--primary-color);
  font-size: 20px;
  margin-right: 10px;
}

.route-line {
  position: relative;
  height: 2px;
  background-color: #dcdfe6;
  margin: 20px 0;
  overflow: hidden;
}

.moving-dot {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: var(--primary-color);
  border-radius: 50%;
  top: -4px;
  animation: moveDot 3s linear infinite;
}

@keyframes moveDot {
  0% {
    left: 0;
  }
  100% {
    left: 100%;
  }
}

.delivery-info {
  margin-top: 20px;
  color: var(--text-secondary);
}

.delivery-info p {
  margin: 8px 0;
}

.start {
  color: var(--success-color);
}

.end {
  color: var(--primary-color);
}

/* 确保地图容器在初始化前就有合适的尺寸 */
#container {
  min-height: 0;
  width: 0;
}

.logistics-simple {
  margin: 20px 0;
  
  h3 {
    margin-bottom: 15px;
    color: #333;
  }
  
  .logistics-container {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
}

  .logistics-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .logistics-status {
      display: flex;
      align-items: center;
      color: #409eff;
      font-size: 16px;
      
      i {
        margin-right: 8px;
        font-size: 20px;
      }
    }
  }
  
  .view-logistics-btn {
    margin-left: 15px;
  }
}
</style>

